//
//  MessageMainController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/14.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Localize_Swift
import ZIM
import SnapKit
import JFPopup

class MessageTopCell: UICollectionViewCell {
    public lazy var button: UIButton = {
        let btn = UIButton(type: .custom)
        btn.layer.borderColor = UIColor(hex: "#999999").cgColor
        btn.layer.borderWidth = 1;
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = true;
        btn.setTitle("GLUZ AI", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.isUserInteractionEnabled = false
        btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: -5)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        return btn
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView .addSubview(button);
        button.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class MessageMainController: BaseViewController {
    
    struct MessageTopModel {
        var imageName: String = ""
        var title: String = ""
        var url: String = ""
    }
    
    lazy var dataList: [MessageTopModel] = []
    
    lazy var addItem: UIBarButtonItem = {
        let item = UIBarButtonItem(
            image: "ic_im_add".toImage,
            style: .done,
            target: self,
            action: #selector(createGroupAction)
        )
        item.tintColor = UIColor(hex: "#333333")
        return item
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.dataSource = self;
        collectionView.delegate = self;
        collectionView.showsHorizontalScrollIndicator = false;
        collectionView.register(MessageTopCell.self, forCellWithReuseIdentifier: "MessageTopCell")
        return collectionView;
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initData()
        initNav()
        initUI()
        loginIM()
        showActivityPopup()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadUserInfo()
    }
    
    @objc func createGroupAction() {
        push(IMGroupCreateController())
    }
    
    override func updateLanguageAction() {
        navigationItem.title = "消息".localized()
    }
}

extension MessageMainController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let messageTopModel = dataList[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MessageTopCell", for: indexPath) as! MessageTopCell;
        cell.button.setImage(UIImage(named: messageTopModel.imageName), for: .normal)
        cell.button.setTitle(messageTopModel.title, for: .normal)
        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let messageTopModel = dataList[indexPath.item]
        if (indexPath.item == 2) { // 翻译
            let portalView = TranslationPortalView.loadFromNib()
            portalView.closeBlock = {
                self.popup.dismissPopup()
            }
            portalView.didSelectedItemBlock = { type in
                self.popup.dismissPopup()
                switch type {
                case .realtime:  // 同声传译
                    self.push(RealtimeTranslatorController())
                    
                case .picture:  // 图片翻译
                    self.push(TranslationPictureController())
                    
                case .audio:  // 语音翻译
                    self.push(TranslationAudioController())
                    
                case .word:  // 文字翻译
                    self.push(TranslatorWordController())
                }
                
            }
            
            self.popup.dialog {
                portalView
            }
        } else {
            self.push(BaseWebViewController(url: messageTopModel.url, isNavBarHide: true))
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15);
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.width - 30 - 30) / 3.0, height: 35)
    }
    
}

private extension MessageMainController {
    func initData() {
        dataList = [
            MessageTopModel(imageName: "ai_icon", title: "GLUZ AI", url: H5UrlManager.deepseekUrl),
            MessageTopModel(imageName: "add_friend", title: "加好友".localized(.login), url: H5UrlManager.addFriendUrl),
            MessageTopModel(imageName: "fanyi_icon", title: "翻译机".localized(.login), url: ""),
        ];
    }
    
    
    func initNav() {
        navigationItem.title = "消息".localized()
        navigationItem.leftBarButtonItem = nil
        // ZIMKit().imKitConfig.navigationBarColor = UIColor.clear
    }
    
    func initUI() {
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(view.snp.top).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(35)
        }
    }
    
    func loginIM() {
        ZIMKit.connectUser(
            userID: String(UserProfile.userId),
            userName: UserProfile.username,
            avatarUrl: UserProfile.avatar
        ) { [self] error in
            if error.code != .ZIMErrorCodeSuccess {
                xLog("[IM] 登录失败 \(error.message)")
                return
            }
            xLog("[IM] 登录成功")
            let conversationListVC = ZIMKitConversationListVC()
            conversationListVC.delegate = self
            addChild(conversationListVC)
            view.addSubview(conversationListVC.view)
            conversationListVC.view.snp.makeConstraints { make in
                make.top.equalTo(collectionView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview().offset(-xIphoneTabBarSafeHeight)
            }
        }
    }
    
    
    func loadUserInfo() {
        let target = LoginAPI.user(String(UserProfile.userId))
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                if let userInfo = dataDictionary["userInfo"] as? [String: Any], let isCreateGroup = userInfo["isim"] as? Int {
                    if isCreateGroup == 1 {
                        // 可以创建群聊
                        self.navigationItem.rightBarButtonItem = self.addItem
                    } else {
                        self.navigationItem.rightBarButtonItem = nil
                    }
                }
            case .failure: break
            }
        }
    }
    
    func showActivityPopup() {
        ActivityPopupManager.shared.getActivityPopup { [weak self] model in
            guard let self = self, let model = model else { return }
            
            // 检查是否应该显示弹窗
            guard ActivityPopupManager.shared.shouldShowPopup(model) else { return }
            
            DispatchQueue.main.async {
                let popupView = ActivityPopupView()
                
                // 根据类型配置弹窗
                let popupType: ActivityPopupView.PopupType = model.type == 1 ? .image : .video
                popupView.configure(type: popupType, 
                                  imageUrl: model.img_url, 
                                    videoUrl: model.video_url, second: model.video_secnd)
                
                // 设置回调
                popupView.closeBlock = { [weak self] in
                    xLog("弹窗关闭回调被调用")
                    popupView.removeFromSuperview()
                    // 记录弹窗显示
                    ActivityPopupManager.shared.recordPopupShow(model)
                }
                
                popupView.imageTapBlock = {
                    // 图片点击事件 - 留空
                    xLog("图片弹窗被点击")
                }
                
                popupView.videoTapBlock = {
                    // 视频点击事件 - 留空
                    xLog("视频弹窗被点击")
                }
                
                popupView.frame = UIScreen.main.bounds
                xKeyWindow.addSubview(popupView)
            }
        }
    }
}

extension MessageMainController: ZIMKitConversationListVCDelegate {
    func conversationList(_ conversationListVC: ZIMKitConversationListVC, didSelectWith conversation: ZIMKitConversation, defaultAction: () -> ()) {
        push(ZIMKitMessagesListVC(conversationID: conversation.id, type: conversation.type, conversationName: conversation.name))
    }
}
